//
//  AppDelegate.m
//  BeeQuick_19
//
//  Created by 刘家强 on 16/9/22.
//  Copyright © 2016年 CN Team. All rights reserved.
//

#import "AppDelegate.h"
#import <AFNetworkActivityIndicatorManager.h>
#import "CNADModel.h"
#import "CNComitOrderTableViewController.h"
#import "CNMineViewController.h"
#import "CNUserFeedBackViewController.h"
#import "CNTabBarController.h"
#import "CNMineMessageController.h"
#import "CNOrderDetailTableViewController.h"
#import "CNEmptyShopCarView.h"
#import "CNNavViewController.h"

// 短信和语音登陆
#import <SMS_SDK/SMSSDK.h>


#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>

//腾讯开放平台（对应QQ和QQ空间）SDK头文件
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>

//微信SDK头文件
#import "WXApi.h"

//新浪微博SDK头文件
#import "WeiboSDK.h"

//人人SDK头文件
#import <RennSDK/RennSDK.h>

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    __mapManager = [[BMKMapManager alloc]init];
    // 如果要关注网络及授权验证事件，请设定     generalDelegate参数
    BOOL ret = [__mapManager start:@"CzPvFpYfBfDWFNLgl6T74ksUWevHAwmY"  generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    
    // 初始化应用，appKey和appSecret从后台申请得
    [SMSSDK registerApp:@"1750a4397090e" withSecret:@"1b7cb469015f4dd08f8b382371c3d03b"];
//     [SMSSDK registerApp:@"166afd9a969e6" withSecret:@"f67f72d2cee11e6cad01958b65d573b6"];
    
    // 分享
    [self share];
    
    // 显示数据请求标志
    [AFNetworkActivityIndicatorManager sharedManager].enabled = true;
    
    // 初始化window
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    // 设置根控制器的颜色
    self.window.backgroundColor = [UIColor whiteColor];
    
    // 设置根控制器

    self.window.rootViewController = ![self isFirstStart] ? [NSClassFromString(@"CNNewController") new] : [NSClassFromString(@"CNTabBarController") new];

     // 设置keyWindow
    [self.window makeKeyAndVisible];
    
    // 注册切换控制器通知
    [CNNotificationCenter addObserver:self selector:@selector(changRootViewController) name:CNNewVCDidChangeNotifacation object:nil];
    
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(buyCarCount:) name:@"购物车" object:nil];
    
    if ([self isFirstStart]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[SQLiteManager sharedSQLiteManager] beInclude:nil With:0];
        });
    }
    
    
    
    [self ADRequest];
    [self addNotification];
    

    
    return YES;
}

// 切换控制器
- (void)changRootViewController {
    self.window.rootViewController = [NSClassFromString(@"CNTabBarController") new];
}

// 判断是否为第一次启动
- (BOOL)isFirstStart {
    return [[NSUserDefaults standardUserDefaults] boolForKey:isFirstStart];
}

// 请求网络图片&缓存图片机制
- (void)ADRequest {
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:@"7" forKey:@"call"];
    
    // 发起请求
    [[CNHTTPSessionManager sharedManager] request:CNHttpMethodPost componentUrlString:@"ad.json.php" parameters:param completion:^(id response, NSError *error) {
        if (error == nil) {
            CNADModel *model = [CNADModel yy_modelWithJSON:response[@"data"]];
            
            // temp路径
            NSString* tempPath = NSTemporaryDirectory();

            // file路径
            NSString* filePath = [tempPath stringByAppendingPathComponent:@"userAD.archive"];

            // 归档
            [NSKeyedArchiver archiveRootObject:model toFile:filePath];
        }
    }];
}

// share代码
- (void)share {
    /**
     *  设置ShareSDK的appKey，如果尚未在ShareSDK官网注册过App，请移步到http://mob.com/login 登录后台进行应用注册，
     *  在将生成的AppKey传入到此方法中。
     *  方法中的第二个第三个参数为需要连接社交平台SDK时触发，
     *  在此事件中写入连接代码。第四个参数则为配置本地社交平台时触发，根据返回的平台类型来配置平台信息。
     *  如果您使用的时服务端托管平台信息时，第二、四项参数可以传入nil，第三项参数则根据服务端托管平台来决定要连接的社交SDK。
     */
    [ShareSDK registerApp:@"iosv1101"
     
          activePlatforms:@[
                            @(SSDKPlatformTypeSinaWeibo),
                            @(SSDKPlatformTypeWechat),
                            @(SSDKPlatformTypeQQ),
                            @(SSDKPlatformTypeRenren)]
                 onImport:^(SSDKPlatformType platformType)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
             case SSDKPlatformTypeQQ:
                 [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                 break;
             case SSDKPlatformTypeSinaWeibo:
                 [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                 break;
             case SSDKPlatformTypeRenren:
                 [ShareSDKConnector connectRenren:[RennClient class]];
                 break;
             default:
                 break;
         }
     }
          onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo)
     {
         
         switch (platformType)
         {
             case SSDKPlatformTypeSinaWeibo:
                 //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                 [appInfo SSDKSetupSinaWeiboByAppKey:@"568898243"
                                           appSecret:@"38a4f8204cc784f81f9f0daaf31e02e3"
                                         redirectUri:@"http://www.sharesdk.cn"
                                            authType:SSDKAuthTypeBoth];
                 break;
             case SSDKPlatformTypeWechat:
                 [appInfo SSDKSetupWeChatByAppId:@"wx4868b35061f87885"
                                       appSecret:@"64020361b8ec4c99936c0e3999a9f249"];
                 break;
             case SSDKPlatformTypeQQ:
                 [appInfo SSDKSetupQQByAppId:@"100371282"
                                      appKey:@"aed9b0303e3ed1e27bae87c33761161d"
                                    authType:SSDKAuthTypeBoth];
                 break;
             case SSDKPlatformTypeRenren:
                 [appInfo        SSDKSetupRenRenByAppId:@"226427"
                                                 appKey:@"fc5b8aed373c4c27a05b712acba0f8c3"
                                              secretKey:@"f29df781abdd4f49beca5a2194676ca4"
                                               authType:SSDKAuthTypeBoth];
                 break;
             default:
                 break;
         }
     }];
}

#pragma mark 添加购物车通知
- (void)addNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didRemoveProduct) name:CNShopCarDidRemoveProductNSNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(buyNumberChange) name:CNShopCarBuyNumberDidChangeNotification object:nil];
}

//移除购物车数据让tableView直接隐藏 空购物车显示
- (void)didRemoveProduct{

}

//底部价格改变的显示
- (void)buyNumberChange{

}

#pragma mark - KVC 设置 badgeView的动画
-(void)buyCarCount:(NSNotification *)notification
{
    NSInteger count = [notification.userInfo[@"totalCount"] intValue];
    
    CNTabBarController *tab =(CNTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    CNNavViewController *nav = tab.childViewControllers[2];
    
    
    if (count) {
        nav.childViewControllers.firstObject.tabBarItem.badgeValue = @(count).description;
    } else {
        nav.childViewControllers.firstObject.tabBarItem.badgeValue = nil;
    }
    
    [tab.tabBar.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if ([obj isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            UIView *badge = [obj valueForKey:@"_badge"];
            if (badge) {
                
                CABasicAnimation *scaleAni = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
                
                scaleAni.fromValue = @0.2;
                scaleAni.toValue = @1.0;
                //                scaleAni.autoreverses = YES;
                scaleAni.duration = 0.3;
                [badge.layer addAnimation:scaleAni forKey:nil];
            }
        }
    }];
}

@end
